package com.ee.chat.api.interceptor;

import cn.hutool.core.util.StrUtil;
import com.ee.chat.common.dao.HostMapper;
import com.ee.chat.common.entity.Host;
import com.ee.chat.common.entity.UserOperationLog;
import com.ee.chat.common.service.IGeneralService;
import com.ee.chat.common.util.ConstantsUtil;
import com.ndhutu.ee.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 刷新上线时间
 * @Author Shane
 * @Date 2019/10/6 21:19
 */
@Component
public class UserStatusInterceptor implements HandlerInterceptor {
    private Logger log = LoggerFactory.getLogger(UserStatusInterceptor.class);

    @Resource(name = "stringRedisTemplate")
    StringRedisTemplate redisTemplate;
    @Resource
    @Lazy
    HostMapper hostMapper;
    @Lazy
    @Resource
    IGeneralService generalService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getParameter("token");
        if(StrUtil.isEmptyIfStr(token)){
            return true;
        }

        String key = ConstantsUtil.USER_TOKEN + token;
        Object userId = redisTemplate.opsForHash().get(key, "userId");
        if(userId != null){
            String key2 = ConstantsUtil.USER_ONLINE + userId;
            Map<Object, Object> map = redisTemplate.boundHashOps(key2).entries();
            if(map.size() == 0 || map == null){  //上线
                map = new HashMap<>();
                String now = DateUtil.getCurrTimeStr(DateUtil.pattern_general);
                map.put("time", now);
                map.put("online", "3");
                map.put("imNum", "0");
                map.put("up_time", now);
                map.put("down_time", now);
                redisTemplate.opsForHash().putAll(key2, map);

                //添加操作记录
                Host host = hostMapper.selectByUserId(Integer.parseInt(userId+""));
                UserOperationLog onlineLog = new UserOperationLog(Integer.parseInt(userId+""), host == null ? 0 : 1, 2);
                generalService.addUserOperationLog(onlineLog, request);

            }else{
                //刷新在线时间
                redisTemplate.opsForHash().put(key2, "down_time", DateUtil.getCurrTimeStr(DateUtil.pattern_general));
            }

            //更新在线信息
            map.put("time", DateUtil.getCurrTimeStr(DateUtil.pattern_general));
            redisTemplate.opsForHash().putAll(key2, map);
        }

        return true;
    }
}
